package io.renren.modules.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.web.dao.TestpapersonDao;
import io.renren.modules.web.entity.TestpaperEntity;
import io.renren.modules.web.entity.TestpapersonEntity;
import io.renren.modules.web.service.TestpaperService;
import io.renren.modules.web.service.TestpapersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


@Service("testpapersonService")
public class TestpapersonServiceImpl extends ServiceImpl<TestpapersonDao, TestpapersonEntity> implements TestpapersonService {

    @Autowired
    private TestpaperService testpaperService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        String testPaper = (String) params.get("testPaper");

        IPage<TestpapersonEntity> page = this.page(
                new Query<TestpapersonEntity>().getPage(params),
                new QueryWrapper<TestpapersonEntity>()
                        .eq("paper_id", testPaper)
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void deleteTestPaperSon(ArrayList<Long> ids, Long testPaperId) {
        baseMapper.deleteBatchIds(ids);
        List<TestpapersonEntity> list = baseMapper.selectList(new QueryWrapper<TestpapersonEntity>().eq("paper_id", testPaperId));
        if (CollectionUtils.isEmpty(list)) {
            testpaperService.removeById(testPaperId);
        } else {
            int count = list.size();
            Integer totalScore = 0;
            for (TestpapersonEntity testpapersonEntity : list) {
                totalScore += testpapersonEntity.getScore();
            }
            TestpaperEntity entity = testpaperService.getById(testPaperId);
            entity.setNum(count);
            entity.setScore(totalScore);
            testpaperService.updateById(entity);
        }
    }

}